<?php

namespace Frieza\Modules\Comment\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\ArticleCounter;
use Doraemon\cache\BlankCounter;
use Doraemon\cache\GuideCounter;
use Doraemon\cache\PhotoCounter;
use Doraemon\cache\Queue;
use Doraemon\model\CommentLink;
use Doraemon\model\Es\Comment;
use Doraemon\service\User;
use Doraemon\model\Comment as dbComment;
use Doraemon\service\Comment as sComment;
use Doraemon\tools\IdGen;
use Doraemon\tools\IdParse;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Hhzbeads\Point\PointClient;
use Illuminate\Http\Request;
use Doraemon\service\Themis\Log as ThemisLog;
use Doraemon\model\Themis\Log as ThemisLogModel;
use Doraemon\service\MothersDay\BlessConfig;


class CommentController extends Controller
{

    private $comment_status_map = [
        dbComment::STATUS_NORMAL => '正常',
        dbComment::STATUS_DEL => '已删除',
        dbComment::STATUS_ADM_DELETE => '后台删除',
        dbComment::STATUS_OWNER_DELETE => '内容主删除',
        dbComment::STATUS_B1_DELETE => 'B1删除',
    ];


    public function index(Request $request, Content $content)
    {
        $tab = new tab();
        Admin::script($this->delReScript());
        $title = '评论列表';
        $tab->add($title, $this->listData($request));

        return $content
            ->header('评论管理')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }

    public function del($id = 0)
    {
        $status = false;
        $message = "操作失败，删除失败";
        try {
            //批量删除
            if(strstr($id,',')){
                $ids = $id;
                $idsList = explode(',',$ids);
                $idInfos = array();
                foreach ($idsList as $key => $id){
                    $obj_id = substr($id, 0, 16);
                    $uid = IdParse::getUid($obj_id);
                    $comment_id = substr($id, 16);
                    $comment_info = dbComment::getCommentById($comment_id, $obj_id);
                    if (empty($comment_info)){
                        throw new \Exception("评论不存在");
                    }
                    $result = dbComment::admDelComment($obj_id, $comment_id, Admin::user()->id);
                    if(!$result){
                        throw new \Exception("部分删除失败");
                    }
                    $idInfos[$key]['obj_id'] = $obj_id;
                    $idInfos[$key]['uid'] = $uid;
                    $idInfos[$key]['comment_id'] = $comment_id;
                    $idInfos[$key]['type'] = $comment_info['type'];
                }
                foreach($idInfos as $idInfo){
                    $obj_id = $idInfo['obj_id'];
                    $uid = $idInfo['uid'];
                    $comment_id = $idInfo['comment_id'];
                    $type = $idInfo['type'];
                    $this->deleteComment($obj_id, $uid, $comment_id, $type);
                }
                $status = true;
                $message = "删除成功";
            }else{
                $obj_id = substr($id, 0, 16);
                $comment_id = substr($id, 16);
                $uid = IdParse::getUid($obj_id);
                $comment_info = dbComment::getCommentById($comment_id, $obj_id);
                $type = $comment_info['type'];
                if (empty($comment_info)){
                    throw new \Exception("评论不存在");
                }
                $result = dbComment::admDelComment($obj_id, $comment_id, Admin::user()->id);
                if($result){
                    $this->deleteComment($obj_id, $uid, $comment_id, $type);
                    $status = true;
                    $message = "删除成功";
                }
            }
        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        } finally {
            return response()->json(compact('status', 'message'));
        }
    }

    private function delReScript(){
        $script = <<<script
        $('.swal2-styled').click(function(){
            window.location.reload();
        });
script;
        return $script;
    }

    private function deleteComment($obj_id,$uid,$comment_id,$type){
            // 评论删除 删除wiki信息
            $wikiObjType = sComment::getCommentRelateWikiType($obj_id);
            if ($wikiObjType) {
                \Biz\service\wiki\ObjRelateWiki::delCommentRelate($uid, $obj_id, $wikiObjType, $comment_id);
            }

            // 删除链接表信息
            $updateLinkData = array(
                "status" => CommentLink::STATUS_DEL
            );
            CommentLink::update($updateLinkData, ["comments_id" => $comment_id, "obj_id" => $obj_id]);


            $del_count = -1;
            if( isset($type)&& $type == 1){
                $sub_count = (int) dbComment::getSubCount($obj_id, [$comment_id]) ? : 0;
                $del_count -= $sub_count;
            }
            // 如果是图片，回答则图片评论数减一,如果为文章,则文章评论数减一
            if (in_array(IdParse::getType($obj_id), [IdGen::TYPE_PHOTO, IdGen::TYPE_ANSWER])) {
                // 删除评论之后计数器图片评论减1
                PhotoCounter::decreasePhotoCounter($obj_id, PhotoCounter::ACT_COMMENT);
                PhotoCounter::decreasePhotoCounter($obj_id, PhotoCounter::ACT_MASTER_COMMENT, $del_count);
            } else if (IdParse::getType($obj_id) == IdGen::TYPE_ARTICLE) {
                ArticleCounter::decreaseArticleCounter($obj_id, ArticleCounter::ACT_COMMENT);
                ArticleCounter::decreaseArticleCounter($obj_id, ArticleCounter::ACT_MASTER_COMMENT, $del_count);
            } else if (IdParse::getType($obj_id) == IdGen::TYPE_GUIDE) {
                GuideCounter::decreaseGuideCounter($obj_id, GuideCounter::ACT_COMMENT);
                GuideCounter::decreaseGuideCounter($obj_id, GuideCounter::ACT_MASTER_COMMENT, $del_count);
            } else if (IdParse::getType($obj_id) == IdGen::TYPE_BLANK) {
                BlankCounter::decreaseBlankCounter($obj_id, BlankCounter::ACT_COMMENT);
                BlankCounter::decreaseBlankCounter($obj_id, BlankCounter::ACT_MASTER_COMMENT, $del_count);
            }

            //扣除积分
            $event_name = PointConfig::POINT_TYPE_DELCOMMIT;
            $point = '3';
            $source = 'admin';
            $request_id = $source.$event_name.$comment_id;
            $msg['obj_id'] = $comment_id;
            $msg['detail'] = "运营删除评论";
            $ext_info = json_encode($msg, JSON_UNESCAPED_UNICODE);
            PointClient::deductPoint($uid, $point, $event_name, $request_id, $source, $ext_info);

            // 添加到队列，更新搜索图片
            Queue::insertQueue('Comment/delComment', array(
                'obj_id' => $obj_id,
                'cmt_id'=> $comment_id
            ));

        //todo 积福--运营后台删除评论
//        $commentInfo = dbComment::getCommentById($comment_id, $obj_id,DbComment::STATUS_LIST);
//        \Doraemon\amqp\CommunityQueue::insertQueue(BlessConfig::MQ_NAME, [
//            'event_name' => BlessConfig::BLESS_CIRCLE_NOT_COMMENT,
//            'obj_id' => $obj_id,
//            'uid' => $commentInfo['uid'],
//            'c_id' => $comment_id
//        ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);


        // 添加themis日志
            $aOpt = array(
                'admin_id'    => Admin::user()->id,
                'remark'      => "用户的评论涉及禁用词、敏感词，评论已被删除",
                'status'      => ThemisLogModel::STATUS_STOP_COMMENT,
                'action_type' => ThemisLogModel::ACTION_TYPE_ADD_COMMENT,
                'illegal_or_punish' => ThemisLogModel::ACTION_PUNISH,
            );
            $aThemisLog = ThemisLog::fetchThemisLogData($uid, $aOpt);
            ThemisLog::add($aThemisLog);

            return true;
    }


    private function listData(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $search = $request->input('search', []);
        $query = [];
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $query['uid'] = $search['uid'];
        }
        if (!empty($search['obj_id'])) {
            $query['obj_id'] = $search['obj_id'];
        }
        if (!empty($search['content'])) {
            $query['content'] = $search['content'];
        }
        if (!empty($search['date'])) {
            $query['date'] = $search['date'];
        }
        if (!empty($search['is_hot'])) {
            $query['is_hot'] = 1;
        }
        //内容类型评论
        $query['obj_type[<]'] = 100;
        $comment_data = $this->getCommentData($query, $page, $pageSize);
        $gridModel = new pGridDataModel($comment_data['data'], $comment_data['total'], ['perPage' => $pageSize, '']);
        $gridModel->setKeyType('string');
        $gridModel->setKeyName("new_id");

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->paginate($gridModel->getPerPage());

            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.uid', 'uid')->integer()->default($search['uid']);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.obj_id', 'obj_id')->default($search['obj_id']);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.content', '关键字')->default($search['content']);
                });

                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.date', '评论时间')->date()->default($search['date']);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->in('search.is_hot', "热门")->checkbox([
                        '1'    => '',
                    ])->default($search['is_hot']);
                });

                //条件展开
                if ($search) $filter->expand();
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
            });
            $grid->column('id');
            $grid->column('uid', '用户信息')->userBasicInfo();
            $grid->column('is_owner','作者')->using(['0' => '否', '1' => '是']);
            $grid->column('to_uid', 'to用户')->display(function ($uid){
                $userInfo = User::getUser($uid);
                return $userInfo['nick'] ? : '';
            });
            $grid->column('obj_id', '内容信息')->contentBasicInfo();
            $grid->column('content', '内容');
            $grid->column('addtime', '评论时间')->display(function ($addtime) {
                return date("Y-m-d H:i:s", $addtime);
            });
            $grid->column('status', '状态')->using($this->comment_status_map);
            $grid->column('like_num', '点赞数')->display(function (){
                $hot_text = ($this->like_num >= 3) ? "热门" : "";
                return $this->like_num . "|" . $hot_text;
            });
            $grid->disableRowSelector(false);

            $grid->actions(function ($actions) {
                if ($actions->row->status == dbComment::STATUS_NORMAL){
                    // 去掉查看,编辑
                    $actions->disableEdit();
                    $actions->disableView();
                } else {
                    // 去掉查看,编辑，删除
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->disableDelete();
                }
            });
        });

        return $listGrid->render();

    }

    private function getCommentData($query, $page, $pageSize)
    {

        $comment_data = [
            "data" => [],
            "total" => 0
        ];

        if ($query['is_hot']){
            unset($query['is_hot']);
            $query['like_num[>=]'] = 3;
        }

        if ($query['date']){
            $query["addtime[>=]"] = strtotime($query['date']);
            $query["addtime[<=]"] = strtotime($query['date']) + 86400;
        }

        $comment_list = Comment::search($query, $page, $pageSize);
        if ($comment_list && is_array($comment_list)){
            $comment_data = [
                "total" => $comment_list['total'],
                "data" => $comment_list['rows']
            ];
        }
        return $comment_data;
    }

}